import React from 'react'
import { inject, observer } from 'mobx-react'
import { DateSwitch, Button, Icon, Select, Tools, Bubble, Flex, List, InputItem } from 'weaver-mobile'
import { withRouter, Switch, Route } from 'react-router-dom';
import { RouteLayout, SelectPage, Browser, BrowserHrm } from 'weaver-mobile-page';
import { toJS } from 'mobx';
import WeekDatePicker from '../../util/DatePicker';
import { isIOS, filterBR } from '../../util/util';
import HrmWorkplan from '../calendar/hrmWorkplan';
import Detail from '../detail/index';
import moment from 'moment';
const getLabel = Tools.getLabel;
const Item = List.Item;
const { FormItem } = List;
const store = [
  'workplanViewListStore',
  'viewWorkplanStore',
];
@inject(...store)
@withRouter
@observer
export default class OneWeekWorkplan extends React.Component {
  static defaultProps = {
    prefixCls: 'workplan-view-list',
    WIDTH: window.innerWidth,
    hasApWidth: 143,
    noApWidth: 93,
  }
  constructor() {
    super()
    this.state = {
      value: '0',
    }
  }

  componentWillMount() {
    const { doinitUrl, browserHrm2 } = this.props.workplanViewListStore;
    const { pathname } = this.props.location;
    doinitUrl(pathname);
    browserHrm2.setState({ activeKey: '5' });
  }

  componentDidMount() {
    let pathName = this.props.location.pathname
    if(pathName == "/calendar/myCalendar/report/workPlanViewList"||pathName == "/calendar/allCalendar/report/workPlanViewList"||pathName == "/calendar/myCalendar/report/workPlanViewList/detail"){
      window.em && window.em.checkJsApi('changeTitle') && window.em.changeTitle({ title: getLabel(33959,'日程一览表') })
    }
    const { getCalendarData, getWorkPlanWeekGroupSelect, getWorkPlanWeekData, selectedDate, groupId, getBaseData, objType, objIds, workPlanType, doinitUrl } = this.props.workplanViewListStore;
    let p = {
      bywhat: 2, // 日，周，月
      selectDate: selectedDate,
      objType: objType,
      objIds: objIds, // 
      workPlanType: workPlanType,
    };
    // pathname === "/calendar/myCalendar/report/workPlanViewList" && getBaseData('', () => getCalendarData());
    getBaseData('', () => getCalendarData())
    if (window.iNoBounce && window.iNoBounce.isEnabled()) {
      isIOS() && window.iNoBounce.disable(); // 解决ios滑动问题
    }
  }

  componentWillUnmount() {
    if (window.iNoBounce && !window.iNoBounce.isEnabled()) {
      isIOS() && window.iNoBounce.enable(); // 组件卸载后，还原解决ios滑动问题时的设置
    }
    localStorage.removeItem("reportTitle")

  }
  componentWillReceiveProps(nextProps){
    let prePathName = this.props.location.pathname
    let curPathName = nextProps.location.pathname
    if(curPathName&&curPathName!==prePathName){
      if(curPathName == "/calendar/myCalendar/report/workPlanViewList"||curPathName == "/calendar/allCalendar/report/workPlanViewList"||curPathName == "/calendar/myCalendar/report/workPlanViewList/detail"){
        window.em && window.em.checkJsApi('changeTitle') && window.em.changeTitle({ title: getLabel(33959,'日程一览表') })
      }
    }
  }
  componentDidUpdate = () => {
    this.getRightHeightToLeft();
  }

  getRightHeightToLeft = () => {
    const { isStyleX, titleFold, ViewDatas } = this.props.workplanViewListStore;
    const { conf: { ap } } = toJS(ViewDatas);
    let tableRows = document.getElementsByClassName('table-row');
    let infoHrms = document.getElementsByClassName('workplan-item-showname');
    let left = document.getElementsByClassName('tr-left');
    let right = document.getElementsByClassName('tr-right');
    let leftScroll = document.getElementsByClassName('left-scroll')[0];
    let rightScroll = document.getElementsByClassName('right-scroll')[0];
    if (infoHrms && titleFold ===0 ) { // 超出两行点点  60: 两行行的高度 折行
      let flodHeight = 60;
      for (let i = 0; i < infoHrms.length; i++) {
        if (infoHrms[i] && infoHrms[i].clientHeight > flodHeight) {
          let hrminfo = document.getElementsByClassName('workplan-item-showname')[i];
          let height = hrminfo.clientHeight;
          while (height > flodHeight) {
            if (hrminfo.innerText && hrminfo.innerText.length > 100) {
              hrminfo.innerText = hrminfo.innerText.substring(0, 100);
            } else {
              hrminfo.innerText = hrminfo.innerText.substring(0, hrminfo.innerText.length - 5);
            }
            height = document.getElementsByClassName('workplan-item-showname')[i].clientHeight;
          }
          hrminfo.innerText = hrminfo.innerText + '...';
        }
      }
    }
    
    if (!leftScroll || !rightScroll) return;
    // 左侧高度由右侧内容决定
    if (ap) {
      let timeLabel = leftScroll.getElementsByClassName('time-label');
      let trRight = rightScroll.getElementsByClassName('tr-right');
      for(let t in trRight) {
        if (parseInt(t) >= 0) {
          if (timeLabel[t] && trRight[t]) {
            timeLabel[t].style.height = trRight[t].clientHeight + 'px';
          }
        }
      }
    } else {
      let trLeft = leftScroll.getElementsByClassName('tr-left');
      let trRight = rightScroll.getElementsByClassName('tr-right');
      for(let t in trRight) {
        if (parseInt(t) >= 0) {
          if (trLeft[t] && trRight[t]) {
            trLeft[t].style.height = trRight[t].clientHeight + 'px';
          }
        }
      }
    }
  }

  getWorkplanViewList = (params) => {
    params = toJS(params);
    const { getCalendarData } = this.props.workplanViewListStore;

    getCalendarData(params);
  }

  getThisWeek = (e) => {
    const { setState } = this.props.workplanViewListStore;
    let date = new Date();
    let dateString = moment(date).format('YYYY-MM-DD');
    this.getWorkplanViewList({ selectDate: dateString });
    setState({ selectedDate: dateString });
    this.activeStyle(this.refs.weekButton);
  }

  changeDate = (params) => {
    if (0 < parseInt(params, 10) && parseInt(params, 10) < 10) {
      return `0${params}`;
    } else {
      return params;
    }
  }

  doRefresh = () => {
    const { groupId, selectedDate } = this.props.workplanViewListStore;
    this.getWorkplanViewList();
    this.activeStyle(this.refs.dorefresh);
  }

  activeStyle = (v) => {
    if (v) { // 点击样式
      let beforeActive = v.className;
      v.className = `${v.className} active`;
      setTimeout(() => {
        v.className = beforeActive;
      }, 100);
    }
  }

  getHeader = () => {
    let { oneWeekDatas, showNight, showNoon, ViewDatas, selectedDate, layout, setState, weekRangeEndDate } = this.props.workplanViewListStore;
    const { days: { value } } = toJS(ViewDatas);
    let weekStartDate = selectedDate || moment(new Date()).format('YYYY-MM-DD'),
      weekEndDate = weekRangeEndDate;
    const innerWidth = window.innerWidth;
    let marginRight = window.innerWidth > 320 ? '5%' : '';
    let field = [];
    let enStyle = getLabel('15539', '本周').indexOf('week') > -1 ? { 'font-size': '12px' } : '';
    if (value && value[0]) {
      weekStartDate = value[0];
      weekEndDate = value[value.length - 1];
      setState({ weekRangeEndDate: value[value.length - 1] });
    }
    field.push(
      <div key='header'>
        <div className='date-picker' key='date-picker' style={{ marginRight: marginRight }}>
          <WeekDatePicker
            visible={false}
            value={selectedDate}
            startDate={weekStartDate}
            endDate={moment(weekEndDate).format("MM-DD")}
            onChange={(v) => this.onPickerChange(v)}
            onOk={(v) => { this.datePickerOk(v) }}
          />
        </div>
        <div className='week-button' ref='weekButton' key='week-button' style={{ ...enStyle }} onClick={(e) => { this.getThisWeek(e) }}><span>{getLabel('15539', '本周')}</span></div>
        <div className='do-refresh' ref='dorefresh' key='do-refresh' onClick={() => { this.doRefresh() }}><Icon type='refresh' size='xs' /></div>
        <div className='do-select' key='do-select' onClick={() => { this.props.history.push(layout.path) }}><Icon type='filter-o' size='xs' /></div>
      </div>
    )

    return field;
  }

  toPreviewWorkplan = (workid) => {
    const { location: { pathname }, viewWorkplanStore, workplanViewListStore } = this.props;
    // this.props.history.push(pathname + '/detail');
    const { detailLayout } = workplanViewListStore;
    this.props.history.push(detailLayout.path);

    viewWorkplanStore.changeWorkplanID(workid);
    workplanViewListStore.setState({
      status: {
        current: 'preview'
      }
    });
  }

  setArrayToObj = (array) => {
    let obj = {};
    if (Array.isArray(array)) {
      array.forEach(res => {
        obj = {
          [res.begindate]: { ...res }
        };
      });
    }
    return obj;
  }

  getItemWidth = () => {
    const { WIDTH, hasApWidth, noApWidth } = this.props;
    let w = WIDTH;
    let { ViewDatas: { conf: { ap } } } = this.props.workplanViewListStore;
    if (ap) {
      w = WIDTH - hasApWidth - 20;
    } else {
      w = WIDTH - noApWidth - 20;
    }
    return w;
  }

  Fontcolor=(hexColor)=> {
		let rgb = [1, 1, 1]; // read-only  0-1, 0-1, 0-1
	   
    if (hexColor.substr(0, 1) == "#")  hexColor = hexColor.substring(1);
    hexColor = hexColor.toLowerCase();
    let b = new Array();
    for (let x = 0; x < 3; x++) {
        b[0] = hexColor.substr(x * 2, 2)
        b[3] = "0123456789abcdef";
        b[1] = b[0].substr(0, 1)
        b[2] = b[0].substr(1, 1)
        b[20 + x] = b[3].indexOf(b[1]) * 16 + b[3].indexOf(b[2])
    }

    rgb[0]=b[20]/255;
    rgb[1]=b[21]/255;
    rgb[2]=b[22]/255;

    return 0.213 * rgb[0] +
         	  0.715 * rgb[1] +
				   	0.072 * rgb[2]
				 	< 0.5 ? '#FFFFFF' : '#000000';
     
  }

  getContentX = () => {
    let field = [];
    let tableTr = [];
    let leftContent = [];
    let rightContent = [];
    let { oneWeekDatas, showNight, showNoon, ViewDatas, titleFold } = this.props.workplanViewListStore;
    const { membersDatas, days: { value }, memberids, conf: { ap } } = toJS(ViewDatas);
    let dispalyCounts = ap ? 2 : 1; // 需要显示中午，下午数
    oneWeekDatas = toJS(oneWeekDatas);
    let width = ap ? 144 : 94; // 根据是否拆分上下午
    let titleFoldStyle = titleFold === 0 ? { } : {};
    Array.isArray(memberids) && memberids.forEach((hrmobj, i) => {
      let hrm = membersDatas[hrmobj.id];
      leftContent.push(
        <div className='tr-left' key={hrmobj.id}>
          <div className='name' style={{ width: ap ? 'calc(100% - 51px)' : 'calc(100% - 1px)'}}>
            <span>{hrmobj.name}</span>
          </div>
          {ap && <div className='timelabel'>
            <div className='time-label time-label-string'>
              <label>{getLabel(512929, '上午')}</label>
            </div>
            <div className='time-label time-label-string'>
              <label>{getLabel(512930, '下午')}</label>
            </div>
          </div>
          }
        </div>
      )
      let fields = [];

      const setDateItems = (fields, info, t) => {
        Array.isArray(value) && value.map((date) => {
          let workplanItems = [];
      
          hrm && Array.isArray(hrm[info]) && hrm[info].map(v => {
            if (v.begindate === date) {
              const fontColor = this.Fontcolor(v.color);
              if(v.showname) {
                v.showname = filterBR(v.showname);
              }
              workplanItems.push(
                <div className='workplan-item-showname' 
                  onClick={() => this.toPreviewWorkplan(v.id)}
                  style={{ ...titleFoldStyle, background: v.color, color:fontColor }}>{v.showname}</div>
              );
            }
          });

          fields.push(
            <td className={`workplan-item ${info}`} key={date} style={{ width: this.getItemWidth(),}}>
              {workplanItems}
            </td>
          )
          
        })
      }

      for( let t = 0; t < dispalyCounts; t ++ ) {
        if (ap && t==0) {
          setDateItems(fields, 'info', t);
          rightContent.push(
            <tr className='tr-right info' key={'tr' + 'info' + i}>
              {
                fields
              }
            </tr>
          );
          fields = [];
        } else if (ap && t==1) {
          setDateItems(fields, 'info_pm', t);
          rightContent.push(
            <tr className='tr-right info_pm' key={'tr' + 'info_pm' + i}>
              {
                fields
              }
            </tr>
          );
          fields = [];
        } else if (!ap) {
          setDateItems(fields, 'info', t);
          rightContent.push(
            <tr className='tr-right' key={'tr' + 'info' + i}>
              {
                fields
              }
            </tr>
          );
          fields = [];
        }
      }

    
    })

    field.push(
      this.getScrollHeader()
    )
    field.push(
      <div className='scroll-content' key='scroll-content' ref="tableX">
        <div className='left-scroll' onScroll={this.tableXLeft} ref='tableXLeft' style={{ width: width }}>
          {leftContent}
        </div>
        <div className='right-scroll' onScroll={this.tableXRight} ref='tableXRight' style={{ width: (window.innerWidth - width -1) }}>
          <table className='scroll-content'>
            <tbody style={{ display: 'table' }}>
              {rightContent}
            </tbody>
          </table>
        </div>
      </div>
    )

    return field;
  }

  tableXRight = () => {
    if (this.refs.tableXLeft && this.refs.tableXRight && this.refs.headScroll) {
      this.refs.tableXLeft.scrollTop = this.refs.tableXRight.scrollTop;
      this.refs.headScroll.scrollLeft = this.refs.tableXRight.scrollLeft;
    }
  }

  tableXLeft = () => {
    if (this.refs.tableXLeft && this.refs.tableXRight) {
      this.refs.tableXRight.scrollTop = this.refs.tableXLeft.scrollTop;
    }
  }

  headScroll = () => {
    if (this.refs.headScroll && this.refs.tableXRight) {
      this.refs.tableXRight.scrollLeft = this.refs.headScroll.scrollLeft;
    }
  }


  getScrollHeader = () => {
    let field = [];
    let { oneWeekDatas, showNight, showNoon, ViewDatas } = this.props.workplanViewListStore;
    const { days: { title, value }, conf: { ap, dataRule } } = toJS(ViewDatas);
    const { hasApWidth, noApWidth } = this.props;
    let width = ap ? hasApWidth : noApWidth; // 根据是否拆分上下午
    field.push(
      <div className='scroll-header' key='scroll-header'>
        <div className='left' style={{ width: width }}>{dataRule==2 ? getLabel('15525','接收人') : getLabel('882','创建人')}</div>
        <div className='right' ref='headScroll' onScroll={this.headScroll} style={{ width: (window.innerWidth - width -2) }}>
          {Array.isArray(title) && title.map(res => {
            return (
              <div className='workplan-item' key={res} style={{ width: this.getItemWidth() }}>
                <div className='time-label'><span>{res}</span></div>
              </div>
            )
          })}
        </div>
      </div>
    )
    return field;
  }

  getLoadding = () => {
    let field = [];
    field.push(
      <div className='loaidng-icon' key='loading'>
        <Icon type='loading' size='lg' />
      </div>
    );
    return field;
  }

  datePickerOk = (v) => {
    const { groupId } = this.props.workplanViewListStore;
    this.getWorkplanViewList(v, groupId);
  }

  onPickerChange = (v) => {
    let { setState, selectedDate, getCalendarData } = this.props.workplanViewListStore;
    let p = {
      selectDate: v,
    };
    setState({ selectedDate: v });
    getCalendarData(p);
  }

  onConditionSearch = () => {
    let { selectedTypeVal, selectGroupVal, hrmBrowserVal, typeBrowserVal, commonBrowserVal, setState } = this.props.workplanViewListStore;
    selectGroupVal = toJS(selectGroupVal);
    hrmBrowserVal = toJS(hrmBrowserVal);
    typeBrowserVal = toJS(typeBrowserVal);
    commonBrowserVal = toJS(commonBrowserVal);
    if (selectGroupVal && ['1', '2', '3', '6'].indexOf(selectGroupVal[0]) > -1) {
      let objid = [];
      if (selectGroupVal && selectGroupVal[0] === '3') { // 人力资源
        Array.isArray(hrmBrowserVal) && hrmBrowserVal.map(res => {
          objid.push(res.id);
        });
      }
      if (selectGroupVal && (selectGroupVal[0] === '1' || selectGroupVal[0] === '2')) {
        Array.isArray(typeBrowserVal) && typeBrowserVal.map(res => {
          objid.push(res.id);
        });
      }
      if (selectGroupVal && (selectGroupVal[0] === '6')) {
        Array.isArray(commonBrowserVal) && commonBrowserVal.map(res => {
          objid.push(res.id);
        });
      }
      setState({ workPlanType: selectedTypeVal, objType: selectGroupVal, objIds: objid });
      this.getWorkplanViewList({ workPlanType: selectedTypeVal, objType: selectGroupVal, objIds: objid });
    } else {
      setState({ workPlanType: selectedTypeVal, objType: selectGroupVal, objIds: '' });
      this.getWorkplanViewList({ workPlanType: selectedTypeVal, objType: selectGroupVal, objIds: '' });
    }
    this.props.history.push('/calendar/myCalendar/report/workPlanViewList');
  }

  onReset = () => {
    const { setState, selectGroup, dept, subComp } = this.props.workplanViewListStore;
    let val = [];
    if (selectGroup[0].key === '1') {
      val = dept;
    }
    if (selectGroup[0].key === '2') {
      val = subComp;
    }
    setState({ selectedTypeVal: [], selectGroupVal: [selectGroup[0].key], typeBrowserVal: val, selectedTypeLabel: selectGroup[0].showname });
  }

  getSelectFields = () => {
    let { selectGroup, selectedType, selectPage, rangeSelectPage, typeSelectPage,
      selectedTypeVal, selectGroupVal, typeSelectPageVal, setState, selectedTypeLabel,
      browser, browserHrm,browserHrm2, typeVal, dept, subComp, hrmBrowserVal, layoutMyfollow, typeBrowserVal, commonBrowserVal
    } = this.props.workplanViewListStore;
    let group = [];
    let fields = [];
    let isHrmBrowser = false;
    typeSelectPageVal = toJS(typeSelectPageVal);
    selectGroupVal = toJS(selectGroupVal);
    hrmBrowserVal = toJS(hrmBrowserVal);
    typeBrowserVal = toJS(typeBrowserVal);
    selectedTypeVal = toJS(selectedTypeVal);
    if (selectGroupVal && selectGroupVal[0] === '1') { // 部门
      typeVal = '4';
    }
    if (selectGroupVal && selectGroupVal[0] === '2') { // 分部
      typeVal = '164';
    }

    const setVisible = (key) => {
      if (key) {
        return ['1', '2', '3'].indexOf(key) > -1;
      }
      return true;
    }
    fields.push(
      <SelectPage
        options={selectedType}
        store={selectPage}
        valueArray={selectedTypeVal}
        label={getLabel('16094','日程类型') }
        multiChoose
        key='selectpage1'
        onChange={(key, showname) => {
          let keys = [];
          Array.isArray(key) && key.forEach(v => { keys.push(v.key) })
          setState({ selectedTypeVal: keys })
        }}
      />
    )
    fields.push(
      <SelectPage
        options={selectGroup}
        store={rangeSelectPage}
        valueArray={selectGroupVal}
        label={getLabel('124810','人员范围')}
        key='selectpage2'
        onChange={(key, showname) => {
          let keys = [];
          Array.isArray(key) && key.forEach(v => { keys.push(v.key) })
          if (keys[0] === '1') {
            setState({ selectGroupVal: keys, objType: keys[0], selectedTypeLabel: key[0].showname, typeBrowserVal: dept })
          } else if (keys[0] === '2') {
            setState({ selectGroupVal: keys, objType: keys[0], selectedTypeLabel: key[0].showname, typeBrowserVal: subComp })
          } else {
            setState({ selectGroupVal: keys, objType: keys[0], selectedTypeLabel: key[0].showname })
          }
        }}
      />
    )
    // 部门 分部
    selectGroupVal && (selectGroupVal[0] === '1' || selectGroupVal[0] === '2') && setVisible(selectGroupVal[0]) && fields.push(
      <Browser
        key='selectpage3'
        type={ typeVal }
        store={browser}
        label={selectedTypeLabel}
        isSingle={false}
        valueArray={typeBrowserVal}
        onChange={(...arg) => {
          setState({ typeBrowserVal: arg[2], objIds: arg[0] })
        }}
      />
    )
    selectGroupVal && selectGroupVal[0] === '3' && fields.push(
      <BrowserHrm
        key='selectpage3'
        store={browserHrm}
        label={selectedTypeLabel}
        valueArray={hrmBrowserVal}
        onChange={(...arg) => {
          setState({ hrmBrowserVal: arg[2], objIds: arg[0] })
        }}
      />
    )

    selectGroupVal && selectGroupVal[0] === '7' && fields.push( // 我的关注
      <List className="my-follow" key="my-follow">
        <FormItem
          key={'my-follow'}
          label={getLabel('502011','维护关注人')}
          line
          extra={<Icon key="right" type="right" />}
          content={(<InputItem placeholder={getLabel('512666','点击维护关注人')} editable={false} onClick={() => this.props.history.push(layoutMyfollow.path)} />)}
        />
      </List>
    )

    selectGroupVal && selectGroupVal[0] === '6' && fields.push( // 常用组
      <BrowserHrm
        key='common'
        store={browserHrm2}
        label={selectedTypeLabel}
        valueArray={commonBrowserVal}
        isSingle={false}
        activeKey={5}
        tabs={[
          {
            isSearch: false,
            key: '5',
            name: getLabel('81554','常用组'),
            selected: true,
            showOrder: 0
          }
        ]}
        onChange={(...arg) => {
          setState({ commonBrowserVal: arg[2], objIds: arg[0] })
        }}
      />
    )


    group.push(
      <div className='workplanlist-select-conditions' key={'group'}>
        <div className='content'>
          {fields}
        </div>
        <div className='footer'>
          <Flex>
            <Flex.Item>
              <Button onClick={() => this.onReset()}>{getLabel('2022','重置')}</Button>
            </Flex.Item>
            <Flex.Item>
              <Button type='primary' onClick={() => this.onConditionSearch()}>{getLabel(387355, '搜索')}</Button>
            </Flex.Item>
          </Flex>
        </div>
      </div>
    );
    return group;
  }

  render() {
    const { prefixCls } = this.props;
    let { selectGroup, selectedType, loadding, selectedDate, weekStartDate, weekEndDate, init, isStyleX, layout, layoutMyfollow,
      selectedTypeVal, selectGroupVal, typeBrowserVal, detailLayout
    } = this.props.workplanViewListStore;
    let type = isStyleX ? 'x' : 'y';
    selectGroup = toJS(selectGroup);
    selectedType = toJS(selectedType);
    return (
      <div style={{ height: '100%' }}>
        {<div className={`${prefixCls}-container`}>
          <div className={`${prefixCls}-container-head`}>
            {this.getHeader()}
          </div>

          <div className={`${prefixCls}-container-content-${type}`}>
            {this.getContentX()}
          </div>
        </div>}
        {loadding && this.getLoadding()}
        <Switch>
          <Route
            key={layout.id}
            path={layout.path}
            render={() => (
              <RouteLayout>
                <div
                  key="wmPoutePageDemo-workplan-list"
                  className="wm-route-layout wm-demo-route-layout-page"
                >
                  {this.getSelectFields()}
                </div>
              </RouteLayout>
            )}
          />
          <Route
            key={layoutMyfollow.id}
            path={layoutMyfollow.path}
            render={() => (
              <RouteLayout>
                <div
                  key="wmPoutePageDemo-workplan-list"
                  className="wm-route-layout wm-demo-route-layout-page"
                >
                  <HrmWorkplan type={'myFllow'} />
                </div>
              </RouteLayout>
            )}
          />
          <Route
            key={detailLayout.id}
            path={detailLayout.path}
            render={()=>(
              <RouteLayout>
                <div key="111" className="wm-route-layout wm-demo-route-layout-page">
                  <Detail />
                </div>
              </RouteLayout>
            )}
          />
        </Switch>
      </div>
    )
  }
}